//
//  PassengerMangerBodyView.swift
//  AirlineReservation
//
//  Created by Kevin on 2020/1/23.
//  Copyright © 2020 Kevin. All rights reserved.
//

import UIKit

class PassengerMangerBodyView: UIView {
    
    // 删除图片
    private var subUsernames = [UILabel]()
    // 姓名
    private var subIdNumbers = [UILabel]()
    // 身份证号
    private var subDeletePics = [UIButton]()
    
    // MARK: 设置乘机人信息
    public var passengers:[UserInfo]? {
        didSet {
            updateLayout()
        }
    }
    // 回调
    public var complete: ((_ item:Int) -> Void)?
    
    override func layoutSubviews() {
        guard let beans = passengers else {
            return
        }
        var tempHeight:CGFloat = 0
        for i in 0..<beans.count {
            // 删除图片
            let deletePic = UIButton()
            deletePic.tag = i
            deletePic.setImage(UIImage(named: "exclude_18x18"), for: .normal)
            deletePic.frame = CGRect(x: MARGIN, y: MARGIN15 + tempHeight, width: 18, height: 18)
            addSubview(deletePic)
            // 姓名
            if subUsernames.count != beans.count {
                let usernameLabel = UILabel()
                subUsernames.append(usernameLabel)
            }
            let usernameLabel = subUsernames[i]
            usernameLabel.textColor = COLOR_NICE
            usernameLabel.text = beans[i].username
            let userX = deletePic.frame.maxX + MARGIN10
            usernameLabel.font = UIFont.systemFont(ofSize: 14)
            usernameLabel.frame = CGRect(x: userX, y: MARGIN15 + tempHeight, width: MARGIN150, height: MARGIN)
            addSubview(usernameLabel)
            // 身份证号
            if subIdNumbers.count != beans.count {
                let idnumberLabel = UILabel()
                subIdNumbers.append(idnumberLabel)
            }
            let idnumberLabel = subIdNumbers[i]
            let idY = usernameLabel.frame.maxY
            idnumberLabel.text = "身份证号/港澳台居民居住证 " + beans[i].idnumber!
            idnumberLabel.textColor = UIColor.gray
            idnumberLabel.font = UIFont.systemFont(ofSize: 12)
            idnumberLabel.frame = CGRect(x: userX, y: idY + MARGIN8, width: frame.width - userX, height: MARGIN)
            addSubview(idnumberLabel)
            // 下划线
            let line = UIView()
            if i != beans.count - 1 {
                line.backgroundColor = COLOR_LINE
                let lineW = frame.width - MARGIN * 2
                let lineY = idnumberLabel.frame.maxY + MARGIN
                line.frame = CGRect(x: MARGIN, y: lineY, width: lineW, height: 1)
                addSubview(line)
            }
            // 存储高度
            tempHeight = line.frame.maxY
            // 删除图片 添加点击事件
            deletePic.addTarget(self, action: #selector(clickItem(btn:)), for: .touchUpInside)
        }
    }
    
    @objc func clickItem(btn:UIButton) -> Void {
        if let callback = complete {
            callback(btn.tag)
        }
    }
}
